import Vue from "vue"
import VueRouter from "vue-router"

//这里是引入的组件
import Login from "@/components/Login/Login.vue"
import Home from "@/views/Home.vue"
import Mainhome from "@/views/Mainhome.vue"
import Mainnews from "@/views/Mainnews.vue"
import Myalbum from "@/views/Myalbum.vue"
import Picture from "@/views/Picture.vue"
import Register from "@/views/Register.vue"
import Adminhome from "@/views/admin/Adminhome"
Vue.use(VueRouter)

//创建路由实例对象
const router = new VueRouter({
  //路由规则的数组
  routes: [
    { path: "/", component: Login },
    {
      path: "/home",
      component: Home,
      redirect: "/home/mainhome",
      children: [
        { path: "mainhome", component: Mainhome },
        { path: "mainnews", component: Mainnews },
        { path: "myalbum", component: Myalbum },
      ],
    },
    { path: "/pictrue", name: "picturelink", component: Picture },
    { path: "/register", component: Register },
    { path: "/admin", component: Adminhome },
  ],
})

router.beforeEach((to, from, next) => {
  if (to.path === "/" || to.path === "/register") return next()
  // 获取token
  const tokenstr = window.sessionStorage.getItem("token")
  if (!tokenstr) return next("/")
  next()
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

export default router
